#!/bin/bash

# 0 .运行方式: 1 交互式 默认  2. 静默式,根据配置参数自动执行


# 1.分区

##    1. 检测磁盘个数
##    2. 大于1给出选择要选择哪个磁盘来安装
##    3.


# 2. install base



##### User Config Begin #####

COUNTRY="CN" #"AU" "AT" "BD" "BY" "BE" "BA" "BR" "BG" "CA" "CL" "CN" "CO" "HR" "CZ" "DK" "EC" "FI" "FR" "DE" "GR" "HK" "HU" "IS" "IN" "ID" "IR" "IE" "IL" "IT" "JP" "KZ" "LV" "LT" "LU" "MK" "MX" "AN" "NC" "NZ" "NO" "PH" "PL" "PT" "QA" "RO" "RU" "RS" "SG" "SK" "SI" "ZA" "KR" "ES" "SE" "CH" "TW" "TH" "TR" "UA" "GB" "US" "VN"


DiskDev="null"      # 1.null: later Select  2./dev/sd*

#PartConfigure="null";
PartConfigure="boot root swap home"

#PartConfigur：  boot  root    swap   home 的顺序就是 /dev/sda* 的顺序，一定一定要是一致的，不能搞错
# 更改PartConfigure 分区的顺序时也要更改GenPartInfo 中的 DiskPartIndex 序号，要保证和PartConfigure 中顺序一致
# PartName 与　GenPartTable　中的分区表顺序和名字需要一一对应
# Advance Professioal Users
# Custom self partition config
function GenPartInfo()
{

cat << EOF > $GenPartPath
Name    FsType     isFormat   DiskPartIndex       MountPoint    Start(M)      End(M) 
                                                     
boot     fat        1         /dev/sda1      /boot      0             500       
                                                     
root     ext4       1         /dev/sda2      /          500           4000      
                                                     
swap     swap       1         /dev/sda3      swap       4000          4100      
                                                     
home     ext4       1         /dev/sda4      /home      4100          100%      

EOF

}

##### User Config End #####



##### const runtime depend
GenPartPath="/root/part.list"





color_echo()
{
    while (($#!=0))
    do
            case $1 in
                    -b)
                            echo -ne " ";
                    ;;
                    -t)
                            echo -ne "\t";
                    ;;
                    -n)     echo -ne "\n";
                    ;;
                    -black)
                            echo -ne "\033[30m";
                    ;;
                    -red)
                            echo -ne "\033[31m";
                    ;;
                    -green)
                            echo -ne "\033[32m";
                    ;;
                    -yellow)
                            echo -ne "\033[33m";
                    ;;
                    -blue)
                            echo -ne "\033[34m";
                    ;;
                    -purple)
                            echo -ne "\033[35m";
                    ;;
                    -cyan)
                            echo -ne "\033[36m";
                    ;;
                    -white|-gray) echo -ne "\033[37m";
                    ;;
                    -reset)
                            echo -ne "\033[0m";
                    ;;
                    -h|-help|--help)
                            echo "Usage: color_echo -color1 message1 -color2 message2 ...";
                            echo "eg:       color_echo -red [ -blue message1 message2 -red ]";
                    ;;
                    *)
                    echo -ne "$1"
                    ;;
            esac
            shift
    done
}

function _DecideDiskDevice()
{
    DiskNum=`lsblk | grep -E '^sd' | wc -l`
    
    color_echo -green "Found: $DiskNum Disks Device: \n" -reset -n
    lsblk | grep -E '^sd|NAME' | awk '{print $1 "   :    " $4"   :   "$6}'
    
    
    list=""
    for i in `lsblk | grep -E '^sd' | awk '{print $1 "  :   " $4}' | awk '{print $1}'`;
    do
        list="$list $i"
    done
    
    color_echo -yellow "\n\nWhich disk you want install ArchLinux ?(sd*): " -green "$list" -reset -n
    
    color_echo "Plese input:  "
    read choose
    
    
    for i in $list;
    do
        if [ "$i" == "$choose" ];then
            DiskDev="/dev/$i"
            break    
        fi
    done
}
function DecideDiskDevice()
{
   if [ $DiskDev != "null" ];then
        return
   fi
   _DecideDiskDevice
   while [ $DiskDev == "null" ];do
        color_echo -red "\nINPUT ERROR: DiskDev is null, please retry input \n\n\n" -reset -n
        _DecideDiskDevice
   done
}

function FormatMountPartition()
{
        partInfoItem=`cat $GenPartPath | grep -E "^*$1"`
        echo $partInfoItem
        partInfoName=`echo $partInfoItem | awk '{print $1}'`    
        partInfoFstype=`echo $partInfoItem | awk '{print $2}'`
        partInfoIsFormat=`echo $partInfoItem | awk '{print $3}'`        
        partInfoPartIndex=`echo $partInfoItem | awk '{print $4}'`
        partInfoMountPoint=`echo $partInfoItem | awk '{print $5}'`

        if [ $partInfoIsFormat == "1" ];then
            if [ $partInfoFstype == "swap" ];then
                color_echo -reset "mkswap on $partInfoPartIndex" -n
                swapoff $partInfoPartIndex > /dev/null 2>&1
                mkswap $partInfoPartIndex -f
            elif [ $partInfoFstype == "fat" ];then
                color_echo -reset " mkfs.fat on $partInfoPartIndex" -n
                mkfs.fat -F32 $partInfoPartIndex
            else
                color_echo -reset " mkfs.$partInfoFstype on $partInfoPartIndex" -n
                mkfs.$partInfoFstype  $partInfoPartIndex
            fi
        fi

        if [ "$i" == "root" ];then
             umount /mnt > /dev/null 2>&1
             umount $partInfoPartIndex > /dev/null 2>&1
             mount $partInfoPartIndex /mnt
        elif [ "$i" == "swap" ];then
             swapon $partInfoPartIndex
        else
             umount /mnt$partInfoMountPoint > /dev/null 2>&1
             umount $partInfoPartIndex > /dev/null 2>&1
             mkdir -p /mnt$partInfoMountPoint
             mount $partInfoPartIndex /mnt$partInfoMountPoint
        fi
}

function GenPartInfoTable()
{
   partInfo_fixed=0
   rm -rf $GenPartPath
   partInfoNameList=""
   while [ $partInfo_fixed == "0" ];do

       if [ "$PartConfigure" != "null" ];then
            GenPartInfo
            partInfoNameList=$PartConfigure
       else
           color_echo -yellow "Please input new parts info: \n"
           color_echo -cyan "PartName:root,home,boot,swap,etc...\n"
           color_echo "Fstype:ext4,ext3,ext2,fat\n"
           color_echo "IsFormat:0,1\n"
           color_echo "PartIndex:/dev/sd**\n"
           color_echo "MountPoint:/ /boot /home swap\n"
           color_echo "\nPartName    FsType  IsFormat  PartIndex   MountPoint\n\n"
           read partinfo
            
            partInfoName=`echo $partinfo | awk '{print $1}'`    
            partInfoFstype=`echo $partinfo | awk '{print $2}'`
            partInfoIsFormat=`echo $partinfo | awk '{print $3}'`        
            partInfoPartIndex=`echo $partinfo | awk '{print $4}'`     
            partInfoMountPoint=`echo $partInfoItem | awk '{print $5}'`
    
            echo $partinfo >> $GenPartPath
            partInfoNameList="$partInfoNameList $partInfoName"
       fi
       
        color_echo -yellow "PartInfo is ok ?,Please Check again! (yes/no)"
        fdisk -l $DiskDev | grep -iE "^$DiskDev|Disklabel|Disk model|Disk $DiskDev|^Device"
        color_echo -reset -n -n
        cat $GenPartPath
        read yes_no
        
        if [ $yes_no = "yes" ];then
            partInfo_fixed="1"
        fi
       
   done

}

function PartDiskDevice()
{
   if [ $DiskDev == "null" ];then
        color_echo -red "\n ERROR PartDiskDevice: DiskDev is NULL \n\n\n" -reset -n
        exit
   fi
   part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
   diskLabel=`fdisk -l $DiskDev | grep -E "Disklabel type" | awk '{print $3}'`

   echo "partition table:"$diskLabel
   echo "partition number:"$part_num


   while [ $diskLabel != "gpt" ];do
        color_echo "Create GPT partition table on $DiskDev ?(y/n,default:y)\n"
        read yes_no
        if [ "$yes_no" != "n" ];then
            parted -s -a optimal $DiskDev mklabel gpt
            if [ "$?" == "0" ];then
                diskLabel=`fdisk -l $DiskDev | grep -E "Disklabel type" | awk '{print $3}'`          
            fi
        else
            color_echo "\n\nOnly Support GPT partition table in this scripts,Press Ctrl-C Exit.......\n\n" -n
        fi
   done

   part_fixed=0
   while [ $part_fixed == "0" ];do
        if [ $part_num == "0" ];then
            color_echo "\nDon't Found Any partition on $DiskDev\nHow Create Partition you want ?(0/1 default:1)\n       0: Using scripts GenPartInfo\n       1: Using cfdisk\n"
            read yes_no
            if [ "$yes_no" != "0" ];then
                cfdisk $DiskDev    
            elif [ "$PartConfigure" != "null" ];then
                color_echo "Not Supported todo." -n
                GenPartInfo
                #TODO: 添加询问确认信息提示， 将这一段单独拎出来做一个函数
                for i in $PartConfigure;do
                        partInfoItem=`cat $GenPartPath | grep -E "^*$i"`
                        echo $partInfoItem
                        partName=`echo $partInfoItem | awk '{print $1}'`    
                        partStart=`echo $partInfoItem | awk '{print $6}'`
                        partEnd=`echo $partInfoItem | awk '{print $7}'`        
                        parted -s -a minimal $DiskDev mkpart primary $partStart $partEnd
                        part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
                done
            fi
            part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
        else             
            color_echo -yellow "Please Check again parttion info follow, It's OK ?" -green "(yes/no:default: no)\n" -cyan "       YES: partion is ok,don't modify\n       NO: modify parttion again\n\n"
            color_echo -reset
            fdisk -l $DiskDev | grep -iE "^$DiskDev|Disklabel|Disk model|Disk $DiskDev|^Device"
            color_echo -reset -n -n
            color_echo "Plese input:  "
            read yes_no
            if [ "$yes_no" == "yes" ];then
                part_fixed="1"
            else
                color_echo -yellow "Do you want delete all exsit partitions ?" -green "(yes/no:default: no)\n" -cyan "       YES:delete all partition,Create from blank disk\n       NO: modify partition by cfdisk\n\n"
                color_echo -reset
                color_echo "Plese input:  "
                read yes_no
                if [ "$yes_no" == "yes" ];then
                    for part in `fdisk -l $DiskDev | grep -E "^$DiskDev" |awk '{print $1}'`;do
                        #echo "part:    $part"
                        swapoff $part > /dev/null 2>&1
                        umount $part > /dev/null 2>&1
                        part=`echo $part |tr -cd "0-9"`
                        parted -s -a minimal $DiskDev rm $part
                    done
                else
                    cfdisk $DiskDev
                fi
                part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
            fi
        fi
   done

   GenPartInfoTable

   FormatMountPartition root
   for i in  $partInfoNameList;do
        if [ $i != "root" ];then
            FormatMountPartition $i
        fi
   done

   df -h
    
   part_num=`fdisk -l $DiskDev | grep -E "^/dev/$1" | wc -l`
   #fdisk -l $DiskDev 
}

function GenerateSourceMirror
{
        mv /etc/pacman.d/mirrorlist /etc/mirrorlist.bak
        color_echo -green "Conneting www.archlinux.org/mirrorlist get mirrorlist......\n" -reset
        wget https://www.archlinux.org/mirrorlist/\?country=$COUNTRY\&protocol=https -O /etc/pacman.d/mirrorlist.new
        if (! grep -q https /etc/pacman.d/mirrorlist.new);then
            wget https://www.archlinux.org/mirrorlist/\?country=$COUNTRY\&protocol=http -O /etc/pacman.d/mirrorlist.new
        fi
        sed -i 's/#Server/Server/g' /etc/pacman.d/mirrorlist.new
        rm -f rankmirrors.sh
        color_echo -green "Conneting /gitee.com/ykzhai/archlinux/raw/master/rankmirrors.sh ......\n" -reset
        wget https://gitee.com/ykzhai/archlinux/raw/master/rankmirrors.sh
        color_echo -green "Generating mirror list , Please wait............\n" -reset
        bash rankmirrors.sh -n 3 /etc/pacman.d/mirrorlist.new > /etc/pacman.d/mirrorlist
        rm -f rankmirrors.sh
        chmod +r /etc/pacman.d/mirrorlist
        color_echo -green "list mirrors: \n" -reset
        cat /etc/pacman.d/mirrorlist
}


function InstallBaseCore()
{
    pacman -Syy 
    pacstrap /mnt base base-devel --force
    genfstab -U -p /mnt > /mnt/etc/fstab
}
#DecideDiskDevice
#PartDiskDevice

GenerateSourceMirror

InstallBaseCore

rm /mnt/root/arch_config.sh
wget https://gitee.com/ykzhai/archlinux/raw/master/arch_config.sh -O /mnt/root/arch_config.sh
chmod +x /mnt/root/arch_config.sh
arch-chroot /mnt /root/arch_config.sh
#



#read ss







